/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.locanet.view.filter;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;

/**
 *
 * @author Gabriel
 */
public class FileUploadFilter implements Filter{
    String repositoryPath;

    @SuppressWarnings("unchecked")
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        if ((request instanceof HttpServletRequest)) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            if (ServletFileUpload.isMultipartContent(httpRequest)) {
                    //-----------------------------------------------------
                    DiskFileUpload factory = new DiskFileUpload();

                    try {

                        List<FileItem> items = (List<FileItem>) factory.parseRequest(httpRequest);
                        final Map<String, String[]> map = new HashMap<String, String[]>();

                        for (FileItem item : items) {
                            if (item.isFormField())
                                processFormField(item, map);
                            else
                                processFileField(item, httpRequest);
                        }

                        request = FileUploadFilter.wrapRequest(httpRequest, map);

                    } catch (FileUploadException ex) {
                        ServletException servletEx = new ServletException();
                        servletEx.initCause(ex);
                        throw servletEx;
                    }
            }
            chain.doFilter(request, response);
        }
    }

    private void processFormField(FileItem formField,
			Map<String, String[]> parameterMap) {
        String name = formField.getFieldName();
        String value = formField.getString();
        String[] values = parameterMap.get(name);

        if (values == null) {
            // Not in parameter map yet, so add as new value.
            parameterMap.put(name, new String[] { value });
        } else {
            // Multiple field values, so add new value to existing array.
            int length = values.length;
            String[] newValues = new String[length + 1];
            System.arraycopy(values, 0, newValues, 0, length);
            newValues[length] = value;
            parameterMap.put(name, newValues);
        }
    }

    private void processFileField(FileItem fileField, HttpServletRequest request) {
            request.setAttribute(fileField.getFieldName(), fileField);
    }

    private static HttpServletRequest wrapRequest(HttpServletRequest request,
			final Map<String, String[]> parameterMap) {
        return new HttpServletRequestWrapper(request) {
            // inner methods passed as parameters
            public Map<String, String[]> getParameterMap() {
                return parameterMap;
            }

            public String[] getParameterValues(String name) {
                return (String[]) parameterMap.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                if (params == null)
                        return null;
                return params[0];
            }

            public Enumeration<String> getParameterNames() {
                return Collections.enumeration(parameterMap.keySet());
            }
        };
	}

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }
 
}
